package com.yao.helper;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 文件辅助类
 * @author yaoym
 */
public class FileHelper {

	/**
	 * 校验File是否存在
	 * 
	 * @param f
	 * @return true: 存在
	 */
	private static boolean check(File f) {
		return Optional.of(f).map(File::exists).get();
	}

	/**
	 * 校验File是否是目录
	 * 
	 * @param f
	 * @return true: 是目录
	 */
	private static boolean checkDir(File f) {
		if (!check(f)) {
			return false;
		}
		
		return Optional.of(f).map(File::isDirectory).get();
	}
	
	/**
	 * 校验path是否为空
	 * @param path
	 * @return true: 空
	 */
	private static boolean checkPath(String path) {
		return Optional.of(path).map(String::isEmpty).get();
	}

	public static List<File> getChildDirectories(String path) {
		if (checkPath(path)) return null;

		File f = new File(path);
		
		if (!checkDir(f)) return null;

		return Arrays.asList(f.listFiles(File::isDirectory));
	}

	public static List<File> getChildDirectories(String path, String extName) {
		if (checkPath(path)) return null;

		File f = new File(path);
		
		if (!checkDir(f)) return null;
		
		return Arrays.asList(f.listFiles((file, name) -> file.isDirectory() && name.endsWith(extName)));
	}

	static List<File> fullFiles = new LinkedList<>();

	public static List<File> getAllChildFile(File f) {
		String reg = "\\.\\w*";
		Arrays.asList(f.listFiles()).stream().forEach(item -> {
			if (!item.getName().matches(reg)) {
				if (item.isDirectory()) {
					getAllChildFile(item);
				} else {
					fullFiles.add(item);
				}
			}
		});

		return fullFiles;
	}
	
	/**
	 * 读取文件内容
	 * @param path
	 * @return
	 */
	public static String read(String path) {
		try {
			return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
		} catch (IOException e) {
			System.err.println("读取文件失败,"+e);
			return "";
		}
	}

}
